/**
 * 时间分片
 * 处理优先级
 * 批量更新
 */
let expirationTime = 0; // 过期时间
let threshod = 5; // 时间切片
const timeQueue = [];
const taskQueue = [];

export function schedulerCallback(callback) {
  let newTask = { callback }
  taskQueue.push(newTask)
  schedule(flushWork)
}

export function schedule(cb) {
  timeQueue.push(cb)
  postMessage();
}

// 使用微任务延迟更新
export function postMessage() {
  const { port1, port2 } = new MessageChannel();
  port1.onmessage = () => {
    const lem = timeQueue.splice(0, timeQueue.length);
    lem.forEach(c => c());
  }
  port2.postMessage(null)
}

export function flushWork() {
  expirationTime = getCurrentTime() + threshod;
  let currentTask = taskQueue[0]
  while (currentTask && !shouldYield()) {
    const { callback } = currentTask;
    callback();
    taskQueue.shift();
    currentTask = taskQueue[0]
  }
}

export function shouldYield() {
  return getCurrentTime() >= expirationTime
}

export function getCurrentTime() {
  return performance.now()
}

